﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Interop;
using myBoard.App.Model;
using myBoard.App.Components.MagnetsStore.Controllers;
using System.Windows.Threading;
using myBoard.App.Components.MagnetsStore;
using System.Diagnostics;
using System.ComponentModel;

namespace myBoard.App.Components
{
	public partial class MainWindow
	{
        NewUserControl _newUserControl;
        MainScreen _mainScreen;
        DispatcherTimer _sessionTimer;
        Storyboard _hideLoaderSB;
        Storyboard _showLoaderSB;

        public MainWindow()
		{
			this.InitializeComponent();
            _authentificationControl.Visibility = Visibility.Hidden;
            _newUserControl = new NewUserControl();
            _mainScreen = new MainScreen();
            _mainScreen.VerticalAlignment = VerticalAlignment.Top;
            _mainScreen.Margin = new Thickness(0, -28, 0, 0);
            _newUserControl.RegistrationCanceled += new NewUserControl.OnRegistrationCanceled(newUserControl_RegistrationCanceled);
            _newUserControl.RegistrationCompleted += new NewUserControl.OnRegistrationCompleted(newUserControl_RegistrationCompleted);
            _newUserControl.HorizontalAlignment = HorizontalAlignment.Center;
            _newUserControl.VerticalAlignment = VerticalAlignment.Center;
            _authentificationControl.RegisterRequested += new AuthenticationControl.OnRegisterRequested(_authentificationControl_RegisterRequested);
            _authentificationControl.UserSignedIn += new AuthenticationControl.OnUserSignedIn(_authentificationControl_UserSignedIn);
            _authentificationControl.UserSigningIn += new AuthenticationControl.OnUserSigningIn(_authentificationControl_UserSigningIn);
            _authentificationControl.AuthentificationFailed += new AuthenticationControl.OnAuthentificationFailed(_authentificationControl_AuthentificationFailed);
            _topMenuZone.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(_topMenuZone_MouseLeftButtonDown);
            StoreController.StoreMainWindow = this;
            _sessionTimer = new DispatcherTimer();
            _sessionTimer.Interval = new TimeSpan(0, 0, 30);
            _sessionTimer.Tick += new EventHandler(_sessionTimer_Tick);
            this.Closed += new EventHandler(MainWindow_Closed);
            _closeBt.Click += new RoutedEventHandler(_closeBt_Click);
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            _hideLoaderSB = this.Resources["HideLoader"] as Storyboard;
            _showLoaderSB = this.Resources["ShowLoader"] as Storyboard;
		}

        void _authentificationControl_UserSigningIn()
        {
            StoreController.UpdateStatus("Connecting user, please wait ...");
            _pleaseWaitText.Text = "Connecting user, please wait ...";
            _authentificationControl.CustomHide();
            this.BeginStoryboard(_showLoaderSB);
        }

        void _authentificationControl_AuthentificationFailed()
        {
            Storyboard hideLoaderSB = this.Resources["HideLoader"] as Storyboard;
            hideLoaderSB.Completed += (s, e) =>
                {
                    _authentificationControl.CustomShow();
                };
            this.BeginStoryboard(hideLoaderSB);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            CheckStoreAvailabilityAsync();
        }

        private void CheckStoreAvailabilityAsync()
        {
            _preLoader.Start();
            try
            {
                MagnetsStoreClient.StoreClientInitilized += (client) =>
                {
                    Debug.WriteLine("Store client initialized");
                    BackgroundWorker bw = new BackgroundWorker();
                    bw.DoWork += (s, arg) =>
                    {
                        bool result = client.IsStoreOpen();
                        arg.Result = result;
                    };
                    bw.RunWorkerCompleted += (s, arg) =>
                    {
                        Debug.WriteLine("Store is open");
                        if (arg.Error != null)
                            throw new Exception("Cannot to Magnet store", arg.Error);
                        
                        if (Convert.ToBoolean(arg.Result))
                        {
                            _hideLoaderSB.Completed += (sender, e) =>
                            {
                                _authentificationControl.Visibility = Visibility.Visible;
                                _authentificationControl.ConnectToStore();
                            };
                            _hideLoaderSB.Begin();                            
                        }
                        else
                        {
                            myBoard.Framework.Forms.MessageBox.Show("Magnet Store closed", "Sorry the magnet store is currently closed, please try again later.", "Magnet Store", EventLogEntryType.Error, MessageBoxButton.OK);
                        }
                    };
                    bw.RunWorkerAsync();
                };
                MagnetsStoreClient.InitilizeMagnetStoreClient();
            }
            catch (Exception ex)
            {
                myBoard.Framework.Forms.MessageBox.Show("Magnet Store closed",
                    string.Format("Sorry the magnet store is currently closed, please try again later.\r\n{0}", ex.ToString()),
                    "Magnet Store", EventLogEntryType.Error, MessageBoxButton.OK);
            }
        }

        void _closeBt_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            _sessionTimer.Stop();
        }

        void _sessionTimer_Tick(object sender, EventArgs e)
        {
            MagnetsStoreClient.Client.KeepSessionAliveAsync(InstancesSingleton.Instances.UsersViewModel.ConnectedUserSessionId);
        }

        void _topMenuZone_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DragMove();
        }

        void _authentificationControl_UserSignedIn(myBoard.App.MagnetStore.User user)
        {
            this.BeginStoryboard(_hideLoaderSB);
            _contentZone.Child = _mainScreen;
            BindControls();
            InstancesSingleton.Instances.MagnetsViewModel.UpdateLatestMagnetsAsync();
            InstancesSingleton.Instances.MagnetsViewModel.RefreshFeaturedMagnetAsync();
            InstancesSingleton.Instances.MagnetsViewModel.RefreshConnectedUserSubmittedMagnetsAsync();
            InstancesSingleton.Instances.CategoriesViewModel.RefreshUsedCategoriesAsync();
            InstancesSingleton.Instances.CategoriesViewModel.RefreshAllCategories();
            _sessionTimer.Start();
        }

        private void BindControls()
        {
        }

        void _authentificationControl_RegisterRequested()
        {
            _contentZone.Child = _newUserControl;                        
        }

        void newUserControl_RegistrationCompleted(NewUserControl sender)
        {
            myBoard.Framework.Forms.MessageBox.Show("Account successfully created !",
                string.Format("Before you log into the Store, you must first activate your account.\r\nPlease follow instruction we just sent to you at {0}.",
                sender._userEmailTbx.Text),"Magnets Store");
            _contentZone.Child = _authentificationControl;
        }

        void newUserControl_RegistrationCanceled()
        {
            _contentZone.Child = _authentificationControl;
        }        
	}
}